module API::V3
  class Traffics < Grape::API
    params do
      requires :mac, type: String
    end
    resource :traffics do
      post do
        terminal = Terminal.find_by_mac(params[:mac].downcase)
        if terminal and params[:traffic]
          traffic = Traffic.new params[:traffic]
          traffic.flow = traffic_flow_from_params(params[:traffic][:flow])
          traffic.device = terminal
          result = traffic.save
        else
          result = false
        end
        present result: result
      end

      desc "Return traffics used by the terminal and the current limit"
      params do
        requires :mac, type: String, regexp: /\A([a-fA-F0-9]{2}:){5}[a-fA-F0-9]{2}\z/
      end
      get ':mac' do
        # max traffic read from settings.yml
        max_traffic = traffic_flow_from_params(Settings.max_traffic)

        # terminal current traffic equals to zero once not exists
        terminal = Terminal.where(mac: params[:mac]).first
        current_traffic = traffic_flow_from_params(terminal ? terminal.current_traffic : 0)

        # send the response
        present({ 
          total: traffics_friendly_format(max_traffic),
          used: traffics_friendly_format(current_traffic), 
          rest: traffics_friendly_format([max_traffic -  current_traffic, 0].max)
        })
      end

    end
  end
end